/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.spi.jsonser.entity;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.inspur.edp.cef.entity.changeset.AbstractModifyChangeDetail;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.spi.extend.entity.ICefAddedChildEntityExtend;
import com.inspur.edp.cef.spi.extend.entity.ICefEntityExtend;
import com.inspur.edp.cef.spi.jsonser.abstractcefchange.AbstractCefChangeJsonDeserializer;
import com.inspur.edp.cef.spi.jsonser.util.SerializerUtil;

import java.util.HashMap;
import java.util.LinkedHashMap;
import lombok.var;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractEntityChangeJsonDeSerializer extends AbstractCefChangeJsonDeserializer {
    protected String nodeCode;
    protected boolean isRoot;


    public AbstractEntityChangeJsonDeSerializer(String nodeCode, boolean isRoot, List<AbstractEntitySerializerItem> deSerializers) {
        super(deSerializers);
        this.nodeCode = nodeCode;
        this.isRoot = isRoot;
    }

    @Override
    public AbstractModifyChangeDetail createModifyChangeDetail(JsonParser p, DeserializationContext ctxt) throws IOException {
        p.nextToken();
        ModifyChangeDetail rez = new ModifyChangeDetail(p.getValueAsString());
        p.nextToken();
        return rez;
    }

    @Override
    protected void readModifyChangeDetailProperty(JsonParser p, DeserializationContext ctxt, AbstractModifyChangeDetail changeDetail, String propertyName, HashMap changeValues) throws IOException {
        if (innerIsChildObjectCode(propertyName)) {
            readChildModifyChangeDetails(p, ctxt, (ModifyChangeDetail) changeDetail, propertyName);
        } else {
            super.readModifyChangeDetailProperty(p, ctxt, changeDetail, propertyName, changeValues);
        }
    }

    private void readChildModifyChangeDetails(JsonParser p, DeserializationContext ctxt, ModifyChangeDetail changeDetail, String propertyName) throws IOException {
        String nodeCode = getRealChildCode(propertyName);
        AbstractEntityChangeJsonDeSerializer childConverter = innerGetChildConvertor(nodeCode);
        java.util.HashMap<String, IChangeDetail> childChangeDetailDic = new LinkedHashMap<String, IChangeDetail>();
        JsonToken currentToken = p.getCurrentToken();
        p.nextToken();
        while (p.getCurrentToken() == JsonToken.START_OBJECT) {
            Object tempVar = childConverter.readJson(p, ctxt);
            IChangeDetail childChangeDetail = (IChangeDetail) ((tempVar instanceof IChangeDetail) ? tempVar : null);
            childChangeDetailDic.put(childChangeDetail.getDataID(), childChangeDetail);

//            p.getCurrentToken();
            p.nextToken();
        }

        changeDetail.getChildChanges().put(childConverter.nodeCode, childChangeDetailDic);
        //reader.Read();
    }

    private AbstractEntityChangeJsonDeSerializer innerGetChildConvertor(String nodeCode){
        for(Object item : getExtendList()) {
            List<ICefAddedChildEntityExtend> addedChilds = ((ICefEntityExtend)item).getAddedChilds();
            if(addedChilds == null){
                continue;
            }
            for(ICefAddedChildEntityExtend addedChild : addedChilds){
                if(SerializerUtil.isChildCodeEquals(addedChild.getNodeCode(), nodeCode)){
                    return (AbstractEntityChangeJsonDeSerializer)addedChild.getChangeDeserializer();
                }
            }
        }
        var childConverter = buildChildConvertor(nodeCode);
        childConverter.setCefSerializeContext(context);
        List<ICefEntityExtend> extendList = getExtendList();
        if(extendList == null || extendList.size() <1)
            return childConverter;
        for(ICefEntityExtend extend : extendList){
            var childEntity = extend.getChildEntity(nodeCode);
            if(childEntity != null)
                childConverter.addExtend(childEntity);
        }
        return childConverter;
    }

    protected AbstractEntityChangeJsonDeSerializer buildChildConvertor(String nodeCode){
        return getChildEntityConvertor(nodeCode);
    }

    protected abstract AbstractEntityChangeJsonDeSerializer getChildEntityConvertor(String nodeCode);

    private List<String> extendedChildCodes;
    private  boolean innerIsChildObjectCode(String propertyName){
        if (extendedChildCodes == null) {
            extendedChildCodes = new ArrayList();
            for(Object item : getExtendList()) {
                List<ICefAddedChildEntityExtend> addedChilds = ((ICefEntityExtend)item).getAddedChilds();
                if(addedChilds == null){
                    continue;
                }
                for(ICefAddedChildEntityExtend addedChild : addedChilds){
                    extendedChildCodes.add(addedChild.getNodeCode() + "s");
                }
            }
        }
        if(extendedChildCodes.stream()
            .filter(item -> SerializerUtil.isChildCodeEquals(propertyName, item)).findAny().isPresent()){
            return true;
        }
        else{
            return isChildObjectCode(propertyName);
        }
    }

    /**
     * 判断某一个属性名称是否是子对象
     *
     * @param propertyName 属性名称
     * @return 属性是子对象
     */
    protected abstract boolean isChildObjectCode(String propertyName);

    protected String getRealChildCode(String propertyName) {
        String nodeCode = propertyName.substring(0, propertyName.length() - 1);
        return nodeCode;
//        String first = nodeCode.substring(0, 1);
//        String after = nodeCode.substring(1); //substring(1),获取索引位置1后面所有剩余的字符串
//        first = first.toUpperCase();
//        return  first + after;
    }

    protected boolean isPropertiesEquals(String proName1,String propName2)
    {
        if(proName1==null||proName1.equals("")||propName2==null||propName2.equals(""))
            throw new RuntimeException("属性不能为空。");
        return proName1.equalsIgnoreCase(propName2);
    }
}
